package com.peas.platform.common.core.configuration;

import cn.hutool.core.util.ReflectUtil;
import com.peas.platform.common.core.property.SwaggerProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@EnableSwagger2WebMvc
@Slf4j
public class SwaggerConfig {

    @Resource
    private SwaggerProperties swaggerProperties;

    /*
    @Bean
    public Docket docket() {
        Contact contact = new Contact(swaggerProperties.getName(), swaggerProperties.getUrl(), swaggerProperties.getEmail());
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .contact(contact)
                .version(swaggerProperties.getVersion())
                .termsOfServiceUrl(swaggerProperties.getTermsOfService())
                .license(swaggerProperties.getLicense())
                .build();
        Predicate<RequestHandler> selector = RequestHandlerSelectors.none();
        if (CollUtil.isNotEmpty(swaggerProperties.getBasePackage())) {
            log.debug(swaggerProperties.getBasePackage().toString());
            for (String base : swaggerProperties.getBasePackage()) {
                selector = selector.or(RequestHandlerSelectors.basePackage(base));
            }
        } else {
            selector = selector.or(RequestHandlerSelectors.withClassAnnotation(Api.class));
        }
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(selector)
                .paths(PathSelectors.ant("/api/**"))
                .build();
    }

    @Bean
    public static BeanPostProcessor customerBeanPostProcessor() {
        return new BeanPostProcessor() {
            @SuppressWarnings("NullableProblems")
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    List<RequestMappingInfoHandlerMapping> list = getHandlerMappings(bean);
                    if (list != null) {
                        customizeSpringfoxHandlerMappings(list);
                    }
                }
                if (bean instanceof CompatibilityModelMapper) {
                    return createCompatibilityModelMapperProxy(bean);
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectUtil.getField(bean.getClass(), "handlerMappings");
                    if (field == null) {
                        return null;
                    }
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }

            @SuppressWarnings("unchecked")
            private Object createCompatibilityModelMapperProxy(Object bean) {
                ProxyFactory proxyFactory = new ProxyFactory();
                proxyFactory.setProxyTargetClass(true);
                proxyFactory.setTargetClass(bean.getClass());
                proxyFactory.setTarget(bean);
                proxyFactory.addAdvice((MethodInterceptor) invocation -> {
                    Object[] arguments = invocation.getArguments();
                    Method method = invocation.getMethod();
                    if ("modelsFromApiListings".equals(method.getName())) {
                        Map<String, List<ApiListing>> apiListings = (Map<String, List<ApiListing>>) arguments[0];
                        return new SwaggerModelSpecificationMapperImpl().modelsFromApiListings(apiListings);
                    }
                    return invocation.proceed();
                });
                return proxyFactory.getProxy();
            }
        };
    }
    */

    @Bean
    public static BeanPostProcessor customerBeanPostProcessor() {
        return new BeanPostProcessor() {
            @SuppressWarnings("NullableProblems")
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    List<RequestMappingInfoHandlerMapping> list = getHandlerMappings(bean);
                    if (list != null) {
                        customizeSpringfoxHandlerMappings(list);
                    }
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectUtil.getField(bean.getClass(), "handlerMappings");
                    if (field == null) {
                        return null;
                    }
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}
